package chapter4.lessons;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @Project ：learn_java
 * @File ：SellTicketDemo02.java
 * @IDE ：IntelliJ IDEA
 * @Author ：自由如风间
 * @Date ：2025/3/6 16:36
 * @Description ：For study.
 */

public class SellTicketDemo02 implements Runnable {

    private int tickets = 100;

    // 定义一个锁对象
    private final ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        while (true) {
            try {
                lock.lock();
                if (tickets <= 0) {
                    break;
                } else {
                    // Thread.sleep(10);
                    System.out.println(Thread.currentThread().getName() + " 正在卖票，余 " + tickets + " 张");
                    tickets--;
                }
            } finally {
                lock.unlock();
            }
        }
    }

}
